package com.etone.smartAudit.service;

import cn.hutool.crypto.digest.DigestUtil;
import com.etone.smartAudit.domain.Admin;
import com.etone.smartAudit.domain.ProjectFile;
import com.etone.smartAudit.enums.ProjectFileLogType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * 针对 wopi 文档验证监听处理service
 */
@Service
public class OfficeFileService {

    private final static String EDIT_OFFICE = "office_edit_f:";
    @Autowired
    private RedisUtil redisUtil;


    @Autowired
    private ProjectFileVersionService versionService;

    @Autowired
    private ProjectFileLogService projectFileLogService;

    /***
     * 判断用户是否在编辑指定文件
     * @param admin
     * @param fId
     * @return
     */
    public String userIsEdit(Admin admin, Integer fId) {
//        文件状态 文件状态Normal，Edit状态
        //此处监听文件编辑
        StringBuilder sb = new StringBuilder();
        //获取文件id 获取用户id
        String ownerId = String.valueOf(admin.getId());
        String fileId = String.valueOf(fId);
        if (!StringUtils.isEmpty(ownerId) && !StringUtils.isEmpty(fileId)) {
            sb.append("files").append("_").append(fileId);
            String key = String.format("%s%s", EDIT_OFFICE, DigestUtil.md5Hex(sb.toString()));
            if (redisUtil.hasKey(key)) {
                return "Edit";
            }
        }
        return "Normal";
    }

    /***
     * 记录写入状态
     */
    public void writeEditStatus(Integer fileId) {
        //此处监听文件编辑
        StringBuilder sb = new StringBuilder();
        //获取文件id 获取用户id
        if (!StringUtils.isEmpty(fileId)) {
            sb.append("files").append("_").append(fileId);
            String key = String.format("%s%s", EDIT_OFFICE, DigestUtil.md5Hex(sb.toString()));
            if (redisUtil.hasKey(key)) {
                redisUtil.delete(key);
            }
            redisUtil.setEx(key, sb.toString(), 3, TimeUnit.MINUTES);
        }
    }

    /**
     * 解除文件编辑状态
     *
     * @param fileId
     */
    public void removeEditStatus(Integer fileId) {
        StringBuilder sb = new StringBuilder();
        //获取文件id 获取用户id
        if (!StringUtils.isEmpty(fileId)) {
            sb.append("files").append("_").append(fileId);
            String key = String.format("%s%s", EDIT_OFFICE, DigestUtil.md5Hex(sb.toString()));
            if (redisUtil.hasKey(key)) {

                redisUtil.delete(key);
            }
//            redisUtil.setEx(key, sb.toString(), 3, TimeUnit.MINUTES);
        }
    }

    /***
     * 保存历史版本与历史记录
     * @param admin
     * @param file
     */
    public void saveHistoryVersion(Admin admin, ProjectFile file) {
        versionService.copyVersion(file, admin);
        //保存操作历史记录
        //保存日志记录
        projectFileLogService.saveLog(admin, file.getId(), ProjectFileLogType.EDIT.name());
    }
}
